package com.tuomaxu.core;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.startup.Tomcat;

import java.io.File;
import java.io.IOException;

public class SpringApplication {

    public static void run(Class aClass){
        SpringApplication springApplication = new SpringApplication();
        springApplication.run();
    }

    public void run(){
        startTomcat();
    }

    private void  startTomcat(){


        try {
            Tomcat tomcat = new Tomcat();
            tomcat.setPort(8080);
            File baseDir =  createTempDir("tomcat");
            Context context = tomcat.addContext("/", baseDir.getAbsolutePath());
            context.addLifecycleListener((LifecycleListener) Class.forName(tomcat.getHost().getConfigClass())
                    .getConstructor().newInstance());
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private  File createTempDir(String prefix) {
        try {
            File tempDir = File.createTempFile(prefix + ".", "." + "8080");
            tempDir.delete();
            tempDir.mkdir();
            tempDir.deleteOnExit();
            return tempDir;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
